package com.yxc.mambalibrary.http.okhttp;

import com.squareup.okhttp.Response;
import com.yxc.mambalibrary.http.IResponse;
import com.yxc.mambalibrary.http.RequestException;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Response
 * Created by robin on 15/12/4.
 *
 * @author yangxc
 */
public class JsonResponse implements IResponse<JSONObject> {

    private int errCode;
    private String errMsg;
    private JSONObject result;

    public JsonResponse(Response response) {
        try {
            String body = response.body().string();
            result = new JSONObject(body);
        } catch (IOException | JSONException e) {
            result = null;
            errCode = -1;
            errMsg = e.toString();
        }
    }

    @Override
    public JSONObject getResult() {
        return result;
    }

    @Override
    public boolean hasError() {
        return result==null;
    }

    @Override
    public RequestException throwExceptionWhenHasError() {
        return new RequestException(errCode, errMsg);
    }
}
